import Vue from 'vue'
import Vuex from 'vuex'
import Service from '@/service/request'

Vue.use(Vuex)

const getState = () => {
    const permission = localStorage.getItem('permission') || 1
    return {
        userId: 1,
        data: {},
        permission   // 定义用户角色，0：管理员，1：用户
    }
}

export default new Vuex.Store({
    state: getState(),
    mutations: {
        setUserId (state, payload) {
            state.userId = payload
        },
        setData (state, payload) {
            state.data = payload
        },
        setUserPermission (state, payload) {
            state.permission = payload
        }
    },
    actions: {
        async getData ({ commit }) {
            const imgList = [
                require("@/assets/tshirt.png"), 
                require("@/assets/tshirt2.png"), 
                require("@/assets/tshirt3.png")
            ]
            let data = await Service.getHomeData()
            console.log("data >>>>", data)
            if(data.length <= 3) {
                for (let i = 0; i < data.length; i++) {
                    data[i].imgSrc = imgList[i]
                }
            }
            else {
                for (let i = 0; i < imgList.length; i++) {
                    data[i].imgSrc = imgList[i]
                }
                for (let i = imgList.length; i < data.length; i++) {
                    data[i].imgSrc = data[i].img
                }
            }
            
            commit('setData', data)
        }
    }
})
